﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace EffiProz.Core.Lib
{
    public class ReaderInputStream : Stream
    {
        protected TextReader reader;
        protected long    pos;
        int              lastChar = -1;

        public ReaderInputStream(TextReader reader)
        {
            this.reader = reader;
            pos = 0;
        }

        public override int ReadByte()
        {
            if (lastChar >= 0)
            {
                int val = lastChar >> 8;

                lastChar = -1;

                pos++;
                return val;
            }

            char[] buf = new char[1];
           
            int count = reader.Read(buf,0,1);

            if (count == 1)
                lastChar = buf[0];
            else
                lastChar = -1;

            if (lastChar < 0)
            {
                return lastChar;
            }

            pos++;
            return lastChar & 0xff;
        }


        public override int Read(byte[] buffer, int offset, int len)
        {
            int count =0;
            for (count = 0; count < len; count++)
            {
                int val = ReadByte();
                if (val < 0)
                    break;
                buffer[offset + count] = (byte)val;
            }

            return count;
        }

        public override void Close()
        {
            reader.Close();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }


        public override void Flush() { }


        public override long Position
        {
            get
            {
                throw new NotSupportedException();
            }

            set
            {
                throw new NotSupportedException();
            }
        }

        public override long Length
        {
            get
            {
                return 0;
            }
        }

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }

        public override bool CanSeek
        {
            get
            {
                return false;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }
    }
}
